<?php

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Capsule\Manager as DB;

class merchantModel extends Model
{

    protected $table = 'merchant';
    protected $primaryKey = 'id';
    protected $appends = ['role'];

    public function checkUsername($username)
    {
        $member = memberModel::query()->where('phone', $username)->first();
        if($member){
            return $member;
        }
        return false;
    }

    public function checkDianpuStatus($member_id)
    {
        try {
            $merchant = $this->where('member_id', $member_id)->firstOrFail();
            if(dianpuModel::query()->where('id', $merchant->dianpu_id)->where('status', 1)->exists()){
                return true;
            }else{
                return false;
            }
        } catch (Exception $e) {
            return false;
        }
    }

    public function getRolename($roles_id)
    {
        return DB::table('merchant_roles')->where('id', $roles_id)->value('name');
    }

    public function getRoleAttribute()
    {
        return DB::table('merchant_roles')->where('id', $this->attributes['roles_id'])->value('name');
    }

    public function setUserLogin($member_id)
    {
        try {
            $member = memberModel::query()->findOrFail($member_id);
            $merchant = $this->where('member_id', $member_id)->firstOrFail();
            $merchant->logintimes = $merchant->logintimes+1;
            $merchant->logined_at = timestamp();
            $merchant->logined_ip = getIp();
            if(empty($merchant->token) || carbon($merchant->logined_at)->addSeconds(86400)->lt(carbon())){
                $merchant->token = md5($merchant->id . $merchant->dianpu_id . $merchant->is_root . $merchant->logined_at . rand(10000, 99999));
            }
            $res = DB::transaction(function () use ($merchant, $member){
                $merchant->save();
                forget('merchant_auths_' . $merchant->id);
                $data = [
                    'user_id'       => $merchant->id, //店铺店员表ID
                    'roles_id'      => $merchant->roles_id, //店铺用户权限ID
                    'dianpu_id'     => $merchant->dianpu_id, //店铺ID
                    'member_id'     => $member->id, //店铺用户ID
                    'username'      => $member->nickname,
                    'phone'         => $member->phone,
                    'avatar'        => $member->avatar,
                    'merchant_token'=> $merchant->token,
                ];
                global $auth;
                $auth = new Auth(_RBACMerchantCookieKey_);
                $auth->login($data);
                $auth->write();
                return $auth->isLogin(true);
            });
            return $res;
        } catch (Exception $exception){
            return false;
        }
    }

    public function getRoles()
    {
        $rows = DB::table('merchant_roles')->select('id', 'rolename')->get();

        return $rows;
    }

}
